﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Unread.App.Common;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Unread.Business.Models;
using Unread.Business.Repositories.Interfaces;

namespace Unread.App.Views
{
    partial class ExtendedSplash
    {
        private readonly IFeedRepository _feedRepository;
        private SplashScreen _splash;

        private Frame _rootFrame;
        private CoreDispatcher _dispatcher;
        private Rect _splashImageRect;
        private Task<IEnumerable<Feed>> _getAllFeedsTask;

        public ExtendedSplash(IFeedRepository feedRepository, SplashScreen splashscreen, bool loadState)
        {
            InitializeComponent();

            if (feedRepository == null) throw new ArgumentNullException("feedRepository");

            _feedRepository = feedRepository;
            _splash = splashscreen;

            _rootFrame = new Frame();
            _dispatcher = Window.Current.CoreWindow.Dispatcher;

            LoadSplashImage();
            RestoreStateAsync(loadState);

            Window.Current.SizeChanged += new WindowSizeChangedEventHandler(ExtendedSplash_OnResize);
        }

        private void LoadSplashImage()
        {
            if (_splash != null)
            {
                _splash.Dismissed += new TypedEventHandler<SplashScreen, Object>(DismissedEventHandler);

                _splashImageRect = _splash.ImageLocation;
                PositionImage();
            }
        }

        private async void RestoreStateAsync(bool loadState)
        {
            if (loadState)
                await SuspensionManager.RestoreAsync();

            _getAllFeedsTask = _feedRepository.GetAll();
        }

        private void PositionImage()
        {
            extendedSplashImage.SetValue(Canvas.LeftProperty, _splashImageRect.X);
            extendedSplashImage.SetValue(Canvas.TopProperty, _splashImageRect.Y);
            extendedSplashImage.Height = _splashImageRect.Height;
            extendedSplashImage.Width = _splashImageRect.Width;

            progressRing.SetValue(Canvas.TopProperty, _splashImageRect.Y + _splashImageRect.Height + progressRing.ActualHeight);
            progressRing.SetValue(Canvas.LeftProperty, _splashImageRect.X + (_splashImageRect.Width / 2) - progressRing.ActualWidth);
        }

        private void ExtendedSplash_OnResize(Object sender, WindowSizeChangedEventArgs e)
        {
            if (_splash != null)
            {
                _splashImageRect = _splash.ImageLocation;
                PositionImage();
            }
        }

        private async void DismissedEventHandler(SplashScreen sender, object e)
        {
            var hasFeeds = false;

            try
            {
                var allFeeds = await _getAllFeedsTask;
                hasFeeds = allFeeds.Any();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                hasFeeds = false;
            }

            await _dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(() =>
                    {
                        StartApplication(hasFeeds);
                    }));
        }

        private void StartApplication(bool hasFeeds)
        {
            if (hasFeeds)
                _rootFrame.Navigate(typeof(UnreadPage));
            else
                _rootFrame.Navigate(typeof(AddFeedPage));

            Window.Current.Content = _rootFrame;
        }
    }
}
